package com.pswv2.backstage.more.authentication.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.pswv2.backstage.more.authentication.servic.AuthenticationService;
import com.pswv2.backstage.role.service.RoleService;
import com.pswv2.bub.bsc.dao.po.Authentication;
import com.pswv2.bub.bsc.dao.po.Permission;
import com.pswv2.bub.bsc.dao.po.Role;
import com.pswv2.bub.bsc.dao.po.RolePermission;
import com.pswv2.bub.bsc.dao.po.ShareKWord;
import com.pswv2.bub.bsc.dao.po.User;
import com.pswv2.util.BackendErrorCode;
import com.pswv2.util.CommonResp;
import com.pswv2.util.ExtraSpringHibernateTemplate;
import com.pswv2.util.Sessions;
import com.pswv2.util.Strings;

@Controller
@RequestMapping(value = "authenticationAction", produces = { "text/json;charset=UTF-8" })
public class AuthenticationAction {
	
	private static Class<?> poc = Authentication.class;
	private static Class<?> pocU = User.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private AuthenticationService authenticationService;
	
	/**
	 * 是否已上传过认证
	 */
	@ResponseBody
	@RequestMapping(value = "orAuthentication")
	public String orAuthentication(Integer userId) {
		Authentication a=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "userId", userId);
		if(a!=null){
			return CommonResp.buildSuccessResp(a).toJsonString();
		}else{
			return CommonResp.buildErrorResp(BackendErrorCode.not_authentication).toJsonString();
		}
	}
	
	/**
	 * 	pc后台选中通过
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnPass"})
	public String pitchOnPass(@RequestParam(value = "items[]") int[] items){
		for(int a:items){
			Authentication entity = authenticationService.queryById(a);
			if(entity.getStatus()==entity.pass||entity.getStatus()==entity.reject){
				return CommonResp.buildErrorResp(BackendErrorCode.already_auditing).toJsonString();
			}
		}
		for(int a:items){
			Authentication entity = authenticationService.queryById(a);
			entity.setStatus(entity.pass);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 	pc后台选中驳回
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnReject"})
	public String pitchOnReject(@RequestParam(value = "items[]") int[] items){
		for(int a:items){
			Authentication entity = authenticationService.queryById(a);
			if(entity.getStatus()==entity.pass||entity.getStatus()==entity.reject){
				return CommonResp.buildErrorResp(BackendErrorCode.already_auditing).toJsonString();
			}
		}
		for(int a:items){
			Authentication entity = authenticationService.queryById(a);
			entity.setStatus(entity.reject);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 	pc后台删除选中的
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnDelete"})
	public String pitchOnDelete(@RequestParam(value = "items[]") int[] items){
		for(int a:items){
			Authentication entity = authenticationService.queryById(a);
			extraSpringHibernateTemplate.getHibernateTemplate().delete(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 单一删除
	 */
	@ResponseBody
	@RequestMapping(value = { "remove" })
	public String remove(int id) {
		Authentication a = authenticationService.queryById(id);
		if (a == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(a);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 审核通过
	 */
	@ResponseBody
	@RequestMapping(value = "pass")
	public String pass(Integer authenticationId) {
			Authentication a=authenticationService.queryById(authenticationId);
			a.setStatus(Authentication.pass);
			extraSpringHibernateTemplate.getHibernateTemplate().update(a);
			return CommonResp.buildSuccessResp().toJsonString();
	     }
	/**
	 * 审核驳回
	 */
	@ResponseBody
	@RequestMapping(value = "reject")
	public String reject(Integer authenticationId) {
		Authentication a=authenticationService.queryById(authenticationId);
		a.setStatus(Authentication.reject);
		extraSpringHibernateTemplate.getHibernateTemplate().update(a);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查询所有信息
	 */
	@ResponseBody
	@RequestMapping(value = "queryAll")
	public String queryAll() {
		List<Authentication> ls=(List<Authentication>) extraSpringHibernateTemplate.findAll(poc);
		List<Object> list=new ArrayList<>();
		if(ls.size()>0){
			for(Authentication a:ls){
				if(a!=null){
					int userId=a.getUserId();
					User u=extraSpringHibernateTemplate.findFirstOneByPropEq(pocU, "userId", userId);
					Map<String ,Object> map=new HashMap<>();
					map.put("name", u.getName());
					map.put("authenticationId", a.getAuthenticationId());
					map.put("status", a.getStatus());
					list.add(map);
				}
			}
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	/**
	 * 后台通过id查询
	 */
	@ResponseBody
	@RequestMapping(value = "queryById")
	public String queryById(Integer id) {
		Authentication a=authenticationService.queryById(id);
		return CommonResp.buildSuccessResp(a).toJsonString();
	}
	/**
	 * 后台通过id查询
	 */
	@ResponseBody
	@RequestMapping(value = "queryByUserId")
	public String queryByUserId(Integer userId) {
		 List<Authentication> ls=(List<Authentication>)extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Authentication WHERE userId=?", userId);
		 if(ls.size()==0){
			 return CommonResp.buildErrorResp(BackendErrorCode.not_authentication).toJsonString();
		 }else{
			 Authentication a=ls.get(0);
			 return CommonResp.buildSuccessResp(a).toJsonString();
		 }
		
	}
	/**
	 * 查询是否通过认证和资料编辑
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "queryPass")
	public String queryPass(Integer userId) {
		List<User> lss=(List<User>) extraSpringHibernateTemplate.getHibernateTemplate().find("From User where userId=?", userId);
		User ur=lss.get(0);
		List<Authentication> ls=(List<Authentication>)extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Authentication WHERE userId=?", userId);
		if(ls.size()==0){
			return CommonResp.buildErrorResp(BackendErrorCode.not_authentication).toJsonString();
		}else{
			if(ur.getStatue()==null){
				return CommonResp.buildErrorResp(BackendErrorCode.not_data).toJsonString();
			}else if(ur.getStatue()==0){
				return CommonResp.buildErrorResp(BackendErrorCode.not_data).toJsonString();
			}else{
				Authentication a=ls.get(0);
				return CommonResp.buildSuccessResp(a).toJsonString();
			}
		}
		
		
	}
	
	
	/*
	 * app添加认证
	 */
	@ResponseBody
	@RequestMapping(value = "appAdd")
	public String appAdd(int userId) {
		List<Authentication> ls=extraSpringHibernateTemplate.findAllByPropEq(poc, "userId", userId);
		if(ls.size()==0){
			Authentication a=new Authentication();
			a.setUserId(userId);
			a.setStatus(Authentication.wait);
			extraSpringHibernateTemplate.getHibernateTemplate().save(a);
			int authenticationId=a.getAuthenticationId();
			return CommonResp.buildSuccessResp(authenticationId).toJsonString();
		}else{
			Authentication a=ls.get(0);
			extraSpringHibernateTemplate.getHibernateTemplate().update(a);
			int authenticationId=a.getAuthenticationId();
			return CommonResp.buildSuccessResp(authenticationId).toJsonString();
		}
		
	}
	
	/**
	 * 上传身份证
	 * @param name
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"uploadIDCard"})
	public String uploadIDCard(int authenticationId,HttpServletRequest request, HttpSession session, HttpServletResponse response){
		System.out.println(authenticationId);
		try {
			MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> file_list = rq.getFileMap();
			if (file_list != null && file_list.size() > 0) {
				if (file_list.containsKey("inputName")) {
					MultipartFile file = file_list.get("inputName");
					if (file != null) {
						Authentication a=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "authenticationId", authenticationId);
						String fileName = file.getOriginalFilename();
						String newFileName = "";
						String[] desp = fileName.split("\\.");
						if (desp != null && desp.length > 0) {
							String extendName = desp[desp.length - 1];
							newFileName = a.getUserId()+"_IDCard" + "." + extendName;
							File saveFile = new File("C:\\img\\" ,newFileName);
							file.transferTo(saveFile);
						}
						a.setIDCard("/imgUrl/"+newFileName);
						extraSpringHibernateTemplate.getHibernateTemplate().update(a);
						return CommonResp.buildSuccessResp(a).toJsonString();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 上传相片
	 * @param name
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"uploadMePicture"})
	public String uploadMePicture(int authenticationId,HttpServletRequest request, HttpSession session, HttpServletResponse response){
		try {
			MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> file_list = rq.getFileMap();
			if (file_list != null && file_list.size() > 0) {
				if (file_list.containsKey("inputName")) {
					MultipartFile file = file_list.get("inputName");
					if (file != null) {
						String fileName = file.getOriginalFilename();
						String newFileName = "";
						String[] desp = fileName.split("\\.");
						Authentication a=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "authenticationId", authenticationId);
						if (desp != null && desp.length > 0) {
							String extendName = desp[desp.length - 1];
							newFileName = a.getUserId()+"_MePicture" + "." + extendName;
							File saveFile = new File("C:\\img\\" ,newFileName);
							file.transferTo(saveFile);
						}
						a.setMePicture("/imgUrl/"+newFileName);
						extraSpringHibernateTemplate.getHibernateTemplate().update(a);
						return CommonResp.buildSuccessResp(a).toJsonString();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 上传学历证
	 * @param name
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"uploadEducational"})
	public String uploadEducational(int authenticationId,HttpServletRequest request, HttpSession session, HttpServletResponse response){
		try {
			MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> file_list = rq.getFileMap();
			if (file_list != null && file_list.size() > 0) {
				if (file_list.containsKey("inputName")) {
					MultipartFile file = file_list.get("inputName");
					if (file != null) {
						String fileName = file.getOriginalFilename();
						String newFileName = "";
						String[] desp = fileName.split("\\.");
						Authentication a=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "authenticationId", authenticationId);
						if (desp != null && desp.length > 0) {
							String extendName = desp[desp.length - 1];
							newFileName = a.getUserId()+"_Educational" + "." + extendName;
							ServletContext servletContext = request.getSession().getServletContext();
							String uploadPath = servletContext.getRealPath("/") + "upload\\";
							File saveFile = new File("C:\\img\\" ,newFileName);
							file.transferTo(saveFile);
						}
						a.setEducational("/imgUrl/"+newFileName);
						extraSpringHibernateTemplate.getHibernateTemplate().update(a);
						
						return CommonResp.buildSuccessResp(a).toJsonString();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		Authentication a=authenticationService.queryById(authenticationId);
		a.setStatus(Authentication.pass);
		extraSpringHibernateTemplate.getHibernateTemplate().update(a);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
}
